# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_GET, require_POST

from def_user.models import UserInfo


def register(request):
    return render(request, 'def_user/register.html')

def login(request):
    return render(request, 'def_user/login.html')

@require_POST
def register_handle(request):
    post = request.POST
    uname = post.get('user_name')
    print uname
    pwd = post.get('pwd')
    cpwd = post.get('cpwd')
    email = post.get('email')
    print cpwd
    # 判断两次密码是否一致
    if pwd != cpwd:
        result = dealResponseJson(-1, "两次密码不一致", '')
        return JsonResponse(result)
    user = UserInfo()
    user.uname = uname
    user.upwd = pwd
    user.uemail = email
    user.save()
    result = dealResponseJson(0, "注册成功", '')
    return JsonResponse(result)

@require_POST
def login_handler(request):
    result = {}
    post = request.POST
    name = post.get('username')
    print name
    pwd = post.get('pwd')
    print '密码是'
    print pwd
    user = UserInfo.objects.filter(uname=name).filter(upwd=pwd).first()
    if user:
        data={}
        data['uname'] = user.uname
        result = dealResponseJson(0, '请求成功', data)
    else:
        result = dealResponseJson(-1, '查无此人', '')
    response = JsonResponse(result)
    dealResponse(response)
    return response


#解决跨越请求问题
def dealResponse(response):
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "GET, OPTIONS"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type"

#统一处理返回值格式
def dealResponseJson(code, msg, data):
    result = {}
    result['data'] = data
    result['code'] = code
    result['msg'] = msg
    return result


